package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.config.CacheService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.constants.message.HotArticleConstants;
import com.heima.common.constants.message.UpdateArticleMess;
import com.heima.common.constants.user.UserRelationConstants;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {


    @Autowired
    CacheService cacheService;

    @Autowired
    KafkaTemplate kafkaTemplate;
    /**
     * 存储点赞喜欢数据
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1 参数校验
        if (dto == null || dto.getArticleId() == null || checkParam(dto)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2 获取登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3 点赞/取消点赞
        if (dto.getOperation().intValue() == 0) {
            // 是否已点赞
            Double score = cacheService.zScore(UserRelationConstants.BEHAVIOR_LIKE + user.getId(), dto.getArticleId().toString());
            if (score != null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "已点赞");
            }
            // 点赞
            cacheService.zAdd(UserRelationConstants.BEHAVIOR_LIKE + user.getId(), dto.getArticleId().toString(), System.currentTimeMillis());



            //**********实时计算消息**********************

            UpdateArticleMess mess =
                    new UpdateArticleMess(UpdateArticleMess.UpdateArticleType.LIKES, dto.getArticleId());
            kafkaTemplate.send(HotArticleConstants.HOTARTICLE_SCORE_INPUT_TOPIC, JSON.toJSONString(mess));
            log.info("LIKES:{}", mess);
            //******************************************



        }else {
            // 取消点赞
            cacheService.zRemove(UserRelationConstants.BEHAVIOR_LIKE + user.getId(), dto.getArticleId().toString());
        }

        //4 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 检查参数
     * @return
     */
    private boolean checkParam(LikesBehaviorDto dto){
        if(dto.getType() > 2 || dto.getType() < 0 || dto.getOperation() > 1 || dto.getOperation() < 0){
            return true;
        }
        return false;
    }
}
